package br.nextfm.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.nextfm.dao.AlbumDao;
import br.nextfm.dao.ArtistaDao;
import br.nextfm.model.Album;
import br.nextfm.model.Artista;

public class CadastraAlbumServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String nome = request.getParameter("nome");
		String descricao = request.getParameter("descricao");
		String tags = request.getParameter("tags");
		String imagem = request.getParameter("foto");
		
		int ano = Integer.parseInt(request.getParameter("ano"));
		int idArtista = Integer.parseInt(request.getParameter("artista"));
		
		AlbumDao dao = new AlbumDao();
		ArtistaDao artistaDao = new ArtistaDao();
		
		Album album = new Album(ano, nome, imagem, descricao, tags);
		Artista artista = artistaDao.get(idArtista);
		
		album.setArtista(artista);
		artista.getAlbuns().add(album);
		
		if (dao.insert(album)) {
		
			artistaDao.update(artista);
		
		}
		
		else {
			
			request.setAttribute("erroCadastraAlbum", true);
			
		}
		
		request.setAttribute("albums", dao.getAll());
		request.setAttribute("artistas", artistaDao.getAll());
		request.getRequestDispatcher("album.jsp").forward(request, response);
		
	}

}
